package com.hfut.wxy.common.interceptor;

import com.hfut.wxy.common.exception.WxyException;
import com.hfut.wxy.common.utils.JwtUtil;
import com.hfut.wxy.common.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//登录拦截器
@Component
public class TokenInterceptor implements HandlerInterceptor {
    private static RedisUtil redisUtil;

    @Autowired
    public void setRedisUtil(RedisUtil redisUtil) {
        TokenInterceptor.redisUtil = redisUtil;
    }

    public static final String HEADER_AUTH = "Authorization";
    public static final String TOKEN = "token:";
    public static final long EXPIRED_TIME = 60*15;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        String token = request.getHeader(HEADER_AUTH);
        Claims claims = JwtUtil.validateToken(token);
        Integer userId = claims.get("userId", Integer.class);
        boolean hashKey = redisUtil.hasKey(TOKEN+userId);
        if (hashKey){
            redisUtil.expire(TOKEN+userId, EXPIRED_TIME);
            return true;
        }
        //失效
        throw WxyException.of("4002");
    }
}
